package fun.codedesign.principle.advice151.a113;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 不要在finallly中处理返回值 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-09 19:50
 * @since 1.0.0
 */
public class FinallyReturn {

    // 建议113： 不要在finally块中处理返回值
    /*
     *  不要在finally上return，这样会导致异常无法抛出，导致后续逻辑分析困难
     *  try块执行已经有return语句了，那么就不会再往下执行了
     */
    @Test
    public void test113() throws IOException {
        FileInputStream inputStream = null;
        try {
            System.out.println("try Before块");
            inputStream = new FileInputStream("///");
            System.out.println("try After块");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("执行catch块");
        } finally {
            System.out.println("执行finally块");
            if(inputStream != null) {
                inputStream.close();
            }
        }
    }

    @Test
    public void test113b() throws IOException {
        FileInputStream inputStream = null;
        try {
            System.out.println("try Before块");
            inputStream = new FileInputStream(".");
            System.out.println("try After块");
        } catch (FileNotFoundException e) {
            System.out.println("执行catch块");
            throw e;
        } finally {
            System.out.println("执行finally块");
            if(inputStream != null) {
                inputStream.close();
            }
            return; // 这里return将导致throw e 无法执行
        }
    }
}
